// @Author mohanlan
// @Date 2017年4月10日 下午2:06:24

define(['jquery', 
        'koala'], 
  function($) {

    // input search
    function InputSearch(options) {
      
      this.generated = false;           // 是否初始化成功

      var defaults = {
        //        time: 1000,             // ajax call delay time(ms)
        method: 'GET',                    // ajax call type
        jsonpArgu: 'jsonpCallback',       // json callback arguments
        url: '',                          // ajax call url
        org: 'company',                          // ajax call org parameter
        queryName: 'code',                    // default query name for user enter value
        ajaxData: {},                     // ajax call extra data
        valueName: 'search-result',       // hidden input name
        value: ["id"],                    // hidden input values, value1 - value2 - value3
        display: ["code", "name"]         // search input display value, displayValue1 - displayValue2 -displayValu3
      };
      
      this.options = $.extend( {}, defaults, options);
    }

    // generate input search
    InputSearch.prototype.generate = function(beforeCall, afterCall) {
      
      var that = this;
      
      that.options.url = that.options.url === '' ? 
                         that.input.data("url") : that.options.url;
      
      that.options.valueName = that.options.valueName === 'search-result' ? 
                               (that.input.data('value-name') === undefined ? that.input.attr("name") + '-' + that.options.valueName : that.input.data('value-name')) :
                               that.options.valueName;
      
      that.options.org = that.options.org === '' ?
                         that.input.data('org') : that.options.org;
      
      that.options.queryName = that.options.queryName === '' ? that.input.attr("name") : that.options.queryName;
      
      if(typeof that.options.url === 'undefined' || that.options.url === null || that.options.url === '') {
        console.log("%cKoalaSearch:please add required search url!!!", "background: #222; color: red");
        return;
      }

      that.generateSearch();
      that.generateMethod(beforeCall, afterCall);
      that.generated = true;
    }

    
    InputSearch.prototype.generateSearch = function() {
      
      var that = this;
      if($("input[name='"+that.options.valueName+"']").length == 0 ) {
        $(that.input).after("<input type='hidden' name='"+ that.options.valueName +"' />");
      }
      
      // 按enter键查询
//      $(that.input).on('keyup', function(e){
//        if (e.keyCode == 13) {
//          that.search();
//        }
//      })
      
      $(that.input).on('focus', function(){
        var form = that.input.parents("form");
        var submitButton = $(form).find("button[type='submit']");
        submitButton.attr("disabled", true);
      })
      
      $(that.input).on('blur', function(){
        var form = that.input.parents("form");
        var submitButton = $(form).find("button[type='submit']");
        if($(this).val().trim() != '') {
          that.search();
        } else {
          submitButton.attr("disabled", false);
        }
      })

      //定时查询逻辑
      //$(that.input).koala({delay: that.options.time, keyup: function(event){that.search()}});
      
    }

    // generate input search data
    InputSearch.prototype.generateMethod = function(beforeCall, afterCall) {
      
      var that = this;

      that.onBeforeSearch = that.options.before || beforeCall || function() {
        console.log("input search before function");
      };

      that.onAfterSearch = that.options.success || afterCall || function() {
        console.log("input search success function");
      };
    }

    // display input search
    InputSearch.prototype.value = function(value, displayValue) {
      var that = this;
      that.input.val(displayValue);
      $(that.options.valueName).val(value);
    }

    InputSearch.prototype.search = function() {
      
      var that = this;
          that.onBeforeSearch();
          that.showSearch();
      var form = that.input.parents("form");
      var submitButton = $(form).find("button[type='submit']");

      var ajaxOptions = that.generateSearchOptions();
      
      var request = $.ajax(ajaxOptions);
       
      request.done(function(response) {
        
        submitButton.attr("disabled", false);
        
        console.log(typeof response);

        response = typeof response === 'string' ? JSON.parse(response) : response
        that.onAfterSearch();
        that.input.popover('destroy');
        
        if(response.code === '0') {
          
          that.showData(response.data);
          
        } else {
          
          that.popOverSettings.content = function() {
            var width = that.input.width() + 100;
            return "<p class='koala-search-error text-danger' style='max-width: "+ width +"px;'>" + response.message + "</p>";
          }
          
          setTimeout(function(){
            that.input.popover(that.popOverSettings);
            that.input.popover('show');
          }, 200)
          
          setTimeout(function(){
            that.input.popover('destroy');
            $("input[name='" + that.options.valueName + "']").val("");
            console.log(that.input.val());
            that.input.val("");
          }, 2200)
        }
      });
       
      request.fail(function( jqXHR, textStatus ) {
        console.log( "Request failed: " + textStatus );
        
        that.popOverSettings.content = function() {
          var width = that.input.width() + 100;
          return "<p class='koala-search-error text-danger' style='max-width: "+ width +"px;'>查询失败</p>";
        }
        
        that.input.popover('destroy');
        setTimeout(function(){
          that.input.popover(that.popOverSettings);
          that.input.popover('show');
        }, 200)
        
        setTimeout(function(){
            that.input.popover('destroy');
            $("input[name='" + that.options.valueName + "']").val("");
            console.log(that.input.val());
            that.input.val("");
          }, 2200)
      });

    }

    InputSearch.prototype.generateSearchOptions = function() {
      
      var that = this;

      var result     = {};
      var inputName = that.options.queryName;
      var inputValue = that.input.val();
      var $ajaxData  = Object.prototype.toString.call(that.options.ajaxData)=== '[object Function]' ? 
                       that.options.ajaxData() : that.options.ajaxData;
      
      inputValue.indexOf("-") > -1 ? inputValue = inputValue.split("-")[0].trim() : inputValue;
      
      if(that.input.data('org') !== undefined) {
        var values = $("[name='"+that.input.data('org')+"']").val();
        if(typeof values === 'string') {
          $ajaxData = $.extend( {}, $ajaxData, {"orgIds": values});
        }else if(Object.prototype.toString.call(values) === '[object Array]') {
          $ajaxData = $.extend( {}, $ajaxData, {"orgIds": values.join(",")});
        }
      }

      if(that.options.method === 'GET') {
        
        var url = that.options.url + "?" + inputName + "=" + inputValue;

        $.each($ajaxData, function(key, value) {
          url = url + "&" + key + "=" + value;
        });

        result["url"] = url;

      }else if(that.options.method === 'POST') {

        result["url"] = that.options.url;
        
        var data = $.extend( {}, $ajaxData, {inputName : inputValue});
        result["data"] = data;

      }else if(that.options.method === 'JSONP') {
        
        var url = that.options.url + "?" + inputName + "=" + inputValue;
        $.each($ajaxData, function(key, value) {
          url = url + "&" + key + "=" + value;
        });

        result["url"] = url;

        result["jsonpCallback"] = that.options.jsonpArgu;
      }

      result["method"] = that.options.method;

      return result;
    }

    InputSearch.prototype.showSearch = function() {
      
      var that = this;
          that.popOverSettings = {
            placement: 'bottom',
            container: 'body',
            html: true,
            selector: that.input[0],
            content: function () {
              var width = that.input.width() + 100;
              return "<p class='koala-searching' style='max-width: "+ width +"px;'>查询中&nbsp;<img style='width: 20px; height: 20px;' src='"+ window.__CTX__.resource +"/images/ellipsis.gif' /></p>";
            }
          }

      that.input.popover(that.popOverSettings);
      that.input.popover('show');
    }


    InputSearch.prototype.showData = function(data) {
      
      var that = this;
      
      var value = '';
      for(var i in that.options.value) {
        
        var valueKey = that.options.value[i];
        var item = data[valueKey];
        
        if(item === '' || item === undefined) {
          
          that.popOverSettings.content = function() {
            var width = that.input.width() + 100;
            return "<p class='koala-search-error text-danger' style='max-width: "+ width +"px;'>无匹配数据</p>";
          }
          
          that.input.popover('destroy');
          setTimeout(function(){
            that.input.popover(that.popOverSettings);
            that.input.popover('show');
          }, 200)
          
          return false;
        }
        
        value = value === '' ? (value + item) : (value + ' - ' + item)
      }
      
      var displayValue = '';
      for(var i in that.options.display) {
        
        var displayKey = that.options.display[i];
        var item = data[displayKey];
        
        if(item === '' || item === undefined) {
          
          that.popOverSettings.content = function() {
            var width = that.input.width() + 100;
            return "<p class='koala-search-error text-danger' style='max-width: "+ width +"px;'>无匹配数据</p>";
          }
          
          that.input.popover('destroy');
          setTimeout(function(){
            that.input.popover(that.popOverSettings);
            that.input.popover('show');
          }, 200)
          
          return false;
        }
        
        displayValue = displayValue === '' ? (displayValue + item) : (displayValue + ' - ' + item)
      }
      
      that.input.val(displayValue);
      
      $("input[name='" + that.options.valueName + "']").val(value);
      
      that.input.trigger("koala.search.value.changed");
      
//      var $width = that.input.width() - 60;
//      var $target = that.input.attr("name");
//      var $dataTemplate = "<ul class='koala-search-result' data-target='" +$target+ "' style= 'width:" + $width + "px;'>"
      
//      for(var i in data) {
//        
//        var item = data[i];
//        
//        var value = '';
//        for(var i in that.options.value) {
//          var valueKey = that.options.value[i];
//              value = value === '' ? (value + item[valueKey]) : value + ' ' + item[valueKey]
//        }
//
//        var displayValue = '';
//        for(var i in that.options.display) {
//          var displayKey = that.options.display[i];
//              displayValue = displayValue === '' ? (displayValue + item[displayKey]) : (displayValue + ' ' + item[displayKey])
//        }
//
//        $dataTemplate = $dataTemplate + "<li class='koala-search-item' data-value='"+value+"'><p>"+ displayValue +"</p></li>";
//      }
      
//      $dataTemplate = $dataTemplate + "</ul>"
//      
//      that.popOverSettings.content = $dataTemplate;
//      setTimeout(function(){
//        that.input.popover(that.popOverSettings);
//        that.input.popover('show');
//        that.bindClick();
//      }, 200)
    }

//    InputSearch.prototype.bindClick= function() {
//      
//      var that = this;
//      
//      $(document).on('click', 'li.koala-search-item', function(event) {
//        event.preventDefault();
//        var value = $(this).data('value');
//        var displayValue = $(this).find('p').html();
//        var $target = $(this).parents("ul").data("target");
//        var $targetInput = $("input[name='"+$target+"']")
//        $targetInput.val(displayValue);
//        $targetInput.next().val(value);
//        that.input.popover('destroy');
//      });

//    }

    $.fn.koalaSearch = function(options, beforeCall, afterCall) {

      $.koalaSearch = new InputSearch(options);
      
      $.koalaSearch.input = $(this);
      $.koalaSearch.input_id = $(this).attr("id");

      $.koalaSearch.generate(beforeCall, afterCall);
    }
  }
);